package com.ht.WeNas.common;

import lombok.Data;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Data
public class Range {
    Long start;
    Long end;

    /**
     * 获取请求范围对象
     * @param rangeHeader http-range请求头
     * @return 请求返回对象，如果解析请求头失败，则返回null
     */
    public static Range getInstance(String rangeHeader) {
        String regex = "^bytes=(\\d*)-(\\d*)$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(rangeHeader);

        if (!matcher.find()) {
            return null;
        }

        // 获取起始和结束位置
        String startGroup = matcher.group(1);
        String endGroup = matcher.group(2);

        Long start = null;
        Long end = null;
        
        try {
            if (startGroup.isEmpty() && !endGroup.isEmpty()) {
                // 形如 "bytes=-100"
                end = Long.parseLong(endGroup);
                start = -end;
            } else {
                start = Long.parseLong(startGroup);
                end = endGroup.isEmpty() ? null : Long.parseLong(endGroup);
            }
        } catch (NumberFormatException e) {
            return null;
        }
        return new Range(start, end);
    }
    
    public Range(Long start, Long end) {
        this.start = start;
        this.end = end;
    }
}
